package com.xingkeduo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xingkeduo.dao.workpad.TStoreWorkPlanMapper;
import com.xingkeduo.model.po.TStoreWorkPlan;
import com.xingkeduo.model.vo.ShopInfoVo;
import com.xingkeduo.service.OperationService;
import com.xingkeduo.service.StaffAttendanceService;
import com.xingkeduo.service.StorePlanService;
import com.xingkeduo.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 中文输入法发挥不稳定的刘川
 * @Date: 19-3-12 上午10:13
 */
@Service
public class StorePlanServiceImpl implements StorePlanService {

    @Autowired
    TStoreWorkPlanMapper storeWorkPlanMapper;
    @Autowired
    OperationService operationService;
    @Autowired
    StaffAttendanceService attendanceService;


    @Override
    public int insertStorePlan(TStoreWorkPlan workPlan) {
        int res = storeWorkPlanMapper.insert(workPlan);
        return res;
    }

    @Override
    public int updateStorePlan(TStoreWorkPlan workPlan) {
        int res = storeWorkPlanMapper.updateByPrimaryKey(workPlan);
        return res;
    }

    @Override
    public int saveOrUpdateStorePlan(TStoreWorkPlan workPlan) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        int res = 0;
        if (StringUtils.isEmpty(workPlan.getId())) {
            workPlan.setCreator(workPlan.getModifier());
            res = storeWorkPlanMapper.insert(workPlan);
        } else {
            res = storeWorkPlanMapper.updateByPrimaryKey(workPlan);
            Date dateOfMonday = TimeUtil.getDateOfMonday(new Date(), 0);
            //TODO 此处以后需要加 事务处理
            attendanceService.updateAttendanceTypeByStoreId(workPlan.getStoreId(),format.format(dateOfMonday));
        }
        return res;
    }

    @Override
    public String validateWorkTime(TStoreWorkPlan workPlan) {
        StringBuilder res = new StringBuilder();
        if (workPlan.getAllDayShiftEndTime().before(workPlan.getAllDayShiftStartTime()) ||
                workPlan.getAllDayShiftEndTime().compareTo(workPlan.getAllDayShiftStartTime())==0) {
            res.append(" 全班设置失败，下班时间不可早于上班时间");
        }
        if (workPlan.getMorningShiftEndTime().before(workPlan.getMorningShiftStartTime()) ||
                workPlan.getMorningShiftEndTime().compareTo(workPlan.getMorningShiftStartTime())==0) {

            res.append(" 早班设置失败，下班时间不可早于上班时间");
        }
        if (workPlan.getNightShiftEndTime().before(workPlan.getNightShiftStartTime()) ||
                workPlan.getNightShiftEndTime().compareTo(workPlan.getNightShiftStartTime())==0){
            res.append(" 晚班设置失败，下班时间不可早于上班时间");
        }
        return res.toString();
    }

    @Override
    public TStoreWorkPlan getPlanByStoreCode(Long storeCode) {
        return storeWorkPlanMapper.selectPlanByStoreCode(storeCode);
    }

    @Override
    public TStoreWorkPlan getStorePlanByStoreId(Long storeId) {
        TStoreWorkPlan tStoreWorkPlan = storeWorkPlanMapper.selectStorePlanByStoreId(storeId);
        return tStoreWorkPlan;
    }

    @Override
    public List<String> getTimeInterval(Long storeId) {
        //准备请求数据
        JSONObject object = new JSONObject();
        object.put("id", storeId.toString());
        String grain = operationService.grain(object.toString());
        JSONObject jsonObject = JSONObject.parseObject(grain);
        String status = jsonObject.get("status").toString();
        //判断服务返回结果 TODO status=0 暂时返回null
        if ("0".equals(status)) {
            return null;
        }
        String data = jsonObject.get("data").toString();
        // TODO 判断返回结果中是否存在数据 暂时返回null
        if (StringUtils.isEmpty(data)) {
            return null;
        }
        //获取准备数据
        ShopInfoVo shopInfoVo = JSON.parseObject(data, ShopInfoVo.class);
        List<String> timeInterval = new ArrayList<>();
        //判断是否存在 库存颗粒时间
        if(0 == shopInfoVo.getParticle()){
            return null;
        }
        List<String> timeBeforeInterval = TimeUtil.getTimeInterval(shopInfoVo.getDaysList().get(0).getStarttime(), "00:00", shopInfoVo.getParticle());
        List<String> timeAfterInterval = TimeUtil.getTimeInterval(shopInfoVo.getDaysList().get(0).getStarttime(), "24:00", shopInfoVo.getParticle());
        //合并
        for (String time : timeBeforeInterval) {
            timeInterval.add(time);
        }
        timeBeforeInterval.removeAll(timeAfterInterval);
        for (String time : timeAfterInterval) {
            timeInterval.add(time);
        }
        //去重 排序
        Set setTime = new HashSet(timeInterval);
        List tempList = new ArrayList(setTime);
        Collections.sort(tempList);
        return tempList;
    }

    /**
     * @param oneTime 开始时间
     * @param twoTime 结束时间
     * @param minutes 间隔时间（单位分）
     * @return java.util.List<java.lang.String>
     * @throws ParseException
     * @description 旧版本 优化版本在TimeUtil 中
     * @Author 情绪极其不稳定的Shadow
     **/
    private List<String> timeInterval(String oneTime, String twoTime, int minutes) throws ParseException {
        List<String> timeInterval = new ArrayList<>();
        String resultTime = null;
        Date endTime = null;

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        Calendar rightNow = Calendar.getInstance();

        Date startTime = sdf.parse(oneTime);
        Date compareTime = sdf.parse(twoTime);

        //rightNow.setTime(startTime);
        endTime = rightNow.getTime();
        if (compareTime.before(endTime)) {
            while (!endTime.before(compareTime)) {
                rightNow.setTime(startTime);
                rightNow.add(Calendar.MINUTE, -minutes);
                endTime = rightNow.getTime();
                resultTime = sdf.format(endTime);
                startTime = sdf.parse(resultTime);
                timeInterval.add(resultTime);
            }
            return timeInterval;
        } else {
            while (!compareTime.before(endTime)) {
                rightNow.setTime(startTime);
                rightNow.add(Calendar.MINUTE, minutes);
                endTime = rightNow.getTime();
                resultTime = sdf.format(endTime);
                startTime = sdf.parse(resultTime);
                timeInterval.add(resultTime);
            }
            return timeInterval;
        }
    }

}
